<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="目录名称">
        <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入目录名称"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['course:catalogue:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增一级目录
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            icon="Sort"
            plain
            type="info"
            @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 目录列表 -->
    <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="catalogueList"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id"
    >
      <el-table-column label="目录名称" prop="name" width="200px"/>
      <el-table-column label="排序" prop="cindex" width="80"/>
      <el-table-column label="创建时间" prop="createTime" width="180"/>
      <el-table-column label="更新时间" prop="updateTime" width="180"/>
      <el-table-column align="center" label="操作" width="300px">
        <template #default="scope">
          <el-button icon="plus" type="text" @click="handleAdd(scope.row)">添加下级目录</el-button>
          <el-button icon="edit" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button icon="delete" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑目录弹窗 -->
    <el-dialog v-model="open" :title="title" width="400px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属上级目录" prop="parentName">
          <el-tree-select
              v-model="form.parentId"
              :data="catalogueList"
              :props="treeProps"
              filterable
              style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="目录名称" prop="name">
          <el-input v-model="form.name" maxlength="15" placeholder="请输入目录名称"/>
        </el-form-item>

        <el-form-item label="排序" prop="cindex">
          <el-input-number v-model="form.cindex" :min="0"/>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" clearable placeholder="请选择">
            <el-option label="正常" value="1"/>
            <el-option label="禁用" value="2"/>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {ElMessage} from "element-plus"
import * as catalogueApi from '@/api/course/catalogue.js';

export default {
  props: {
    value: {
      type: Number,
    }
  },
  name: 'CatalogueManagement',
  data() {
    return {
      isExpandAll: true,
      refreshTable: true,
      loading: false,
      showSearch: true,
      catalogueOptions: [],
      catalogueList: [],
      treeProps: {
        value: 'id', // 数据中的 value 字段
        label: 'name', // 数据中的 label 字段
        children: 'children' // 数据中的 children 字段
      },
      queryParams: {
        name: undefined
      },
      form: {
        id: this.value,
        parentId: undefined,
        parentName: '',
        name: '',
        level: 1,
        cindex: 1,
        status: 1
      },
      rules: {
        name: [
          {required: true, message: '请输入目录名称', trigger: 'blur'},
          {min: 1, max: 15, message: '目录名称长度不超过15个字符', trigger: 'blur'}
        ],
        level: [
          {required: true, message: '请输入目录级别', trigger: 'blur'}
        ],
        cindex: [
          {required: true, message: '请输入优先级', trigger: 'blur'}
        ]
      },
      open: false,
      title: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  created() {
    this.getList();
    this.isExpandAll = false;
    console.log("index", this.value);

  },
  methods: {
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    getList() {
      this.loading = true;
      this.isExpandAll = false;
      console.log("form", this.form);
      if (this.value !== undefined && this.value === 0) {
        ElMessage.warning('未获取到课程信息');
        return;
      }
      catalogueApi.catalogueTree(this.form.id).then(res => {
        if (res && Array.isArray(res.data) && res.data.length > 0) {
          this.catalogueList = res.data;
          // ElMessage.success('获取目录列表成功' );
          this.loading = false;
        } else {
          this.catalogueList = [];
          ElMessage.warning('没有查询到任何数据');
        }
      }).catch(error => {
        this.loading = false;

        let errorMessage = '获取目录列表失败: 未知错误';
        if (error && error.response && error.response.data) {
          errorMessage = '获取目录列表失败: ' + (error.response.data.message || '无具体错误信息');
          console.error('获取目录列表失败:', error.response.data);
        } else if (error) {
          console.error('请求失败:', error);
          errorMessage = '请求失败: ' + (error.message || '无具体错误信息');
        } else {
          console.error('未知错误');
        }
        ElMessage.error(errorMessage);
      });
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        status: undefined,
        name: undefined
      };
      this.getList();
    },
    reset() {
      this.form = {
        id: undefined,
        parentId: 0,
        name: '',
        level: 1,
        cindex: 1,
        status: '1',
      }
    },
    handleAdd(row) {
      this.reset();
      // catalogueApi.listCatalogue().then(response => {
      //   this.catalogueOptions = proxy.handleTree(response.data, "id");
      // });
      if (row !== undefined) {
        this.form.parentId = row.id;
        this.open = true;
        this.title = "添加目录";
      }
      // this.title = parentNode ? '添加下级目录' : '新增一级目录';
      // this.form = {
      //   id: undefined,
      //   parentId: parentNode ? parentNode.id : 0,
      //   parentName: parentNode ? parentNode.name : '',
      //   name: '',
      //   level: parentNode ? (parentNode.level + 1) : 1,
      //   cindex: 1,
      //   status: 1
      // };
      // this.open = true;
    },
    handleUpdate(row) {
      this.title = '编辑目录';
      this.form = {...row, parentName: row.parentId ? this.getParentName(row.parentId) : ''};
      this.open = true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const apiCall = this.form.id ? catalogueApi.updateCatalogue : catalogueApi.addCatalogue;
          apiCall(this.form).then(response => {
            this.open = false;
            this.getList();
            ElMessage.success(this.form.id ? '更新目录成功' : '新增目录成功');
          }).catch(error => {
            this.loading = false;
            if (error && error.response) {
              ElMessage.error(this.form.id ? '更新目录失败: ' + error.response.data.message : '新增目录失败: ' + error.response.data.message);
              console.error('目录操作失败:', error.response.data);
            } else {
              ElMessage.error(this.form.id ? '更新目录失败: 未知错误' : '新增目录失败: 未知错误');
              console.error('目录操作失败: 未知错误');
            }
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确定要删除此目录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        catalogueApi.delCatalogue(row.id).then(response => {
          this.getList();
          ElMessage.success('删除目录成功');
        }).catch(error => {
          if (error && error.response) {
            ElMessage.error('删除目录失败: ' + error.response.data.message);
            console.error('删除目录失败:', error.response.data);
          } else {
            ElMessage.error('删除目录失败: 未知错误');
            console.error('删除目录失败: 未知错误');
          }
        });
      }).catch(() => {
        ElMessage.info('取消删除');
      });
    },

    getParentName(parentId) {
      const parent = this.catalogueList.find(item => item.id === parentId);
      return parent ? parent.name : '未知目录';
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
